package main.dao;

import main.view.Main;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BookStorageDB {
    public void enterLibrary(String title, String price, String author, String type, String amount, String message ) throws SQLException {
        String sql="Insert into book (title,price,author,type,amount,message) values(?,?,?,?,?,?)";
        Connection con = new Main().getConnection();
        PreparedStatement ps=con.prepareStatement(sql);

        ps.setString(1,title);
        ps.setString(2,price);
        ps.setString(3,author);
        ps.setString(4,type);
        ps.setString(5,amount);
        ps.setString(6,message);

        ps.executeUpdate();

    }
    public void refreshData(String amount) throws SQLException {
        int origin = Integer.parseInt(amount);
        origin -= 1;
        String latest = Integer.toString(origin);
        String sql = "update book set amount = ? where amount = ?";
        Connection con = new Main().getConnection();
        PreparedStatement ps=con.prepareStatement(sql);
        ps.setString(1,latest);
        ps.setString(2,amount);
        int i = ps.executeUpdate();
    }
    public void refreshData(ResultSet rs) throws SQLException {
        String sql = "select * from book where title=?";
        Connection con = new Main().getConnection();
        PreparedStatement ps=con.prepareStatement(sql);
        ps.setString(1,rs.getString(2));
        ResultSet rst = ps.executeQuery();
        while(rst.next()){
            int origin = Integer.parseInt(rst.getString(5));
            origin += 1;
            String latest = Integer.toString(origin);
            String sql1 = "update book set amount = ? where amount = ?";
            PreparedStatement pst = con.prepareStatement(sql1);
            pst.setString(1,latest);
            pst.setString(2,rst.getString(5));
            System.out.println(rst.getString(5));
            System.out.println(latest);
            int i = pst.executeUpdate();
        }
    }
}
